package server

import (
	"controllers"
	"github.com/astaxie/beego/orm"
	"github.com/astaxie/beego"
	"encoding/json"
	"models"
)



// ConsoleScriptController operations for ConsoleScript
type ServerOptController struct {
	controllers.BaseRouter
}


func (c *ServerOptController ) ServerList (){
    o:= orm.NewOrm()
    var allServer []orm.Params
    _,err:=o.Raw("SELECT * FROM gj_server WHERE status = 1").Values(&allServer)
    if err != nil {
	  beego.Info(err.Error())
	  c.SetJson(1,nil,"服务器信息获取失败，失败详情:"+err.Error())
	  return
	}
	c.SetJson(200,allServer,"")
	return
}


func (c *ServerOptController ) AccountList (){
	o:= orm.NewOrm()
	var allAccount []orm.Params
	_,err:=o.Raw("SELECT * FROM gj_server_account ").Values(&allAccount)
	if err != nil {
		beego.Info(err)
		c.SetJson(1,nil,"服务器用户信息获取失败，失败详情:"+err.Error())
		return
	}
	c.SetJson(200,allAccount,"")
	return
}


func (c *ServerOptController ) AddAccount (){
	account := c.GetString("account")
	o:=orm.NewOrm()
	_,err := o.Raw("INSERT INTO gj_server_account (account) VALUES(?)",account).Exec()
	if err != nil {
		beego.Info(err.Error())
		c.SetJson(1, nil, err.Error())
		return
	}
	c.SetJson(200,nil,"用户添加成功")
	return
}


func (c *ServerOptController ) AddServer (){
	if c.User == nil  {
		c.SetJson(2, nil, "not login")
		return
	}

	beego.Info(string(c.Ctx.Input.RequestBody))
	Server := models.GjServer{}
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &Server)
	if err != nil {
		c.SetJson(1, nil, "数据格式错误")
		return
	}
	Server.Operator = c.User.UserName
	_,err = models.AddGjServer(&Server)
	if err != nil {
		beego.Info(err.Error())
		c.SetJson(1, nil, err.Error())
		return
	}

	c.SetJson(200,nil,"服务器添加成功")
	return
}

func (c *ServerOptController) DeleteServer (){
	serverId,_ := c.GetInt("id")
	err := models.DeleteGjServer(serverId)
	if err != nil {
		c.SetJson(1,nil,"删除失败")
		return
	}
	c.SetJson(200,nil,"删除成功")
	return
}